package com.greensecurity.sim.shiro;

import com.greensecurity.sim.entity.Permissions;
import com.greensecurity.sim.entity.Role;
import com.greensecurity.sim.entity.User;
import com.greensecurity.sim.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;


@Slf4j
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private LoginService loginService;
    /**
     * @MethodName doGetAuthorizationInfo
     * @Description 权限配置类
     * @Param [principalCollection]
     * @Return AuthorizationInfo
     * @Author WangShiLin
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        String phone = (String) principalCollection.getPrimaryPrincipal();
        User user = loginService.findByPhone(phone);
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (Role role : user.getRole()) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.getRoleName());
//            log.info( "当前用户角色:"+String.valueOf( role.getRoleName()));
            //添加权限
            for (Permissions permissions : role.getPermissions()) {
//                log.info("当前用户拥有权限:"+String.valueOf( permissions.getPermissionsName()));
                simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
            }
        }
        return simpleAuthorizationInfo;
    }

    /**
     * @MethodName doGetAuthenticationInfo
     * @Description 认证配置类
     * @Param [authenticationToken]
     * @Return AuthenticationInfo
     * @Author WangShiLin
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (StringUtils.isEmpty(authenticationToken.getPrincipal())) {
            return null;
        }
        String phone = authenticationToken.getPrincipal().toString();
        User user = loginService.findByPhone(phone);

        if (user==null) {
            throw new UnknownAccountException("用户信息为空");
        }else
        {
            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(phone, user.getPassword(), getName());

            return simpleAuthenticationInfo;
        }
    }
}
